import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/local'

import Layout from '@/views/Layout'
import Detail from '@/views/Detail'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Article from '@/views/Article'
import Collect from '@/views/Collect'
import Like from '@/views/Like'
import User from '@/views/User'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: 'article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  },
  { path: '/detail', component: Detail },
  { path: '/login', component: Login },
  { path: '/register', component: Register }
]

const router = new VueRouter({
  routes
})
// 路由全局前置导航守卫 - 拦截处理
const whiteList = ['/login', '/register']
// includes()
router.beforeEach((to, from, next) => {
  // 判断是否拥有token
  const token = getToken()
  if (token) {
    next()
  } else {
    // 判断是否是白名单路径
    if (whiteList.includes(to.path)) {
      next() // 直接放行
    } else {
      // 拦截到登录
      next('/login')
    }
  }
})

export default router
